package com.echo.fm.content.activity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.echo.fm.admin.auto.model.Admin;
import com.echo.fm.content.activity.model.Action;
import com.echo.fm.content.activity.model.ActionItem;
import com.echo.fm.content.activity.model.PayType;
import com.echo.util.ErrorException;
import com.echo.util.GsonTools;
import com.echo.util.JSONResult;
import com.echo.util.JsonPagingData;
import com.echo.util.PagingInfo;
import com.echo.util.ResultUtils;
import com.echo.util.SystemWebConstant;
import com.echo.util.TimeGetter;
import com.echo.util.impl.DateUtils;
import com.echo.util.impl.HeaderParser;
import com.echo.util.impl.ValidateUtils;

@Controller
public class IActionController {
	@Autowired
	@Qualifier("actionService")
	IActionService actionService;

	@RequestMapping(value = "/web/action/guide")
	public String actionTemplates(HttpServletRequest request, HttpServletResponse response) {
		return "/pages/content/action/action-add";
	}

	private void initCreateActionpage(HttpServletRequest request) throws ErrorException {

	}

	private void initUpdateActionPage(HttpServletRequest request) throws ErrorException {
		String reqActionId = request.getParameter("id");
		int actionId = Integer.parseInt(reqActionId);
		Action action = actionService.searchActionById(actionId);
		action.setSdate(DateUtils.long2Str(action.getSdateL(), "yyyy-MM-dd HH:mm"));
		action.setEdate(DateUtils.long2Str(action.getEdateL(), "yyyy-MM-dd HH:mm"));
		action.setPayEndTime(DateUtils.long2Str(action.getPayEndTimeL(), "yyyy-MM-dd"));
		List<ActionItem> itemList = actionService.searchActionItemList(actionId);
		request.setAttribute("action", action);
		request.setAttribute("itemJSON", GsonTools.object2String(itemList));
	}

	@RequestMapping(value = "/web/action/addSave", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public Object create(HttpServletRequest request, HttpServletResponse response) {
		try {

			Admin detail = HeaderParser.getUser(request);
			if (detail == null) {
				return ResultUtils.instJSONResult(ResultUtils.WEB_PARAM_ERROR_CODE);
			}
			String appId = request.getParameter("appId");
			Action action = new Action();
			String actionType = request.getParameter("type");
			if (ValidateUtils.isValidInteger(actionType)) {
				action.setActionType(Integer.parseInt(actionType));
			}
			String title = request.getParameter("title");
			if (ValidateUtils.isNotEmpty(title)) {
				action.setTitle(title);
			}
			String image = request.getParameter("image");
			if (ValidateUtils.isNotEmpty(image)) {
				action.setImage(image);
			}
			String sort = request.getParameter("weight");
			if (ValidateUtils.isNotEmpty(sort)) {
				action.setSort(Double.parseDouble(sort));
			}
			String intro = request.getParameter("intro");
			if (ValidateUtils.isNotEmpty("intro")) {
				action.setIntro(intro);
			}
			String url = request.getParameter("url");
			if (ValidateUtils.isNotEmpty("url")) {
				action.setUrl(url);
			}

			String maxAppliment = request.getParameter("maxAppliment");
			if (ValidateUtils.isNotEmpty(maxAppliment)) {
				action.setMaxAppliment(Integer.valueOf(maxAppliment));
			} else {
				action.setMaxAppliment(-1);
			}

			String isTop_str = request.getParameter("istop");
			if (ValidateUtils.isNotEmpty(isTop_str)) {
				action.setLoopStatus(Integer.valueOf(isTop_str));
			} else {
				action.setLoopStatus(0);
			}
			String payStatus = request.getParameter("isPay");
			if (ValidateUtils.isNotEmpty(payStatus)) {
				if ("on".equals(payStatus)) {
					action.setPayStatus(1);
				} else {
					action.setPayStatus(0);
				}
			} else {
				action.setPayStatus(0);
			}

			action.setCdateL(TimeGetter.getTime());
			String sdate = request.getParameter("sdate");
			String edate = request.getParameter("edate");

			if (ValidateUtils.isValidDate(sdate) && ValidateUtils.isValidDate(edate)) {
				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				Calendar calendar = Calendar.getInstance(Locale.CHINA);
				try {
					calendar.setTime(dateFormat.parse(sdate));
				} catch (ParseException e) {
					e.printStackTrace();
				}
				action.setSdateL(calendar.getTimeInMillis());
				try {
					calendar.setTime(dateFormat.parse(edate));
				} catch (ParseException e) {
					e.printStackTrace();
				}
				action.setEdateL(calendar.getTimeInMillis());

			}
			if ("on".equals(payStatus)) {
				String strPayType = request.getParameter("payType");
				if (ValidateUtils.isNotEmpty(strPayType)) {
					Integer payType = Integer.valueOf(strPayType);
					if (PayType.BYCAR.getTypeId() == payType) {
						action.setPayType(PayType.BYCAR.getTypeId());
					} else {
						action.setPayType(PayType.BYPEOPLE.getTypeId());
					}
				}
				String payName = request.getParameter("payName");
				if (ValidateUtils.isNotEmpty(payName)) {
					action.setPayName(payName);
				}
				String payAmount = request.getParameter("pay");
				if (ValidateUtils.isNotEmpty(payAmount)) {
					action.setPayAmount(Float.parseFloat(payAmount));
				}
				String payEndTime = request.getParameter("payEndTime");
				if (ValidateUtils.isValidDate(payEndTime)) {
					action.setPayEndTimeL(DateUtils.str2DateLong(payEndTime));
				}
			} else {
				action.setPayName("");
				action.setPayAmount(0.0f);
				action.setPayEndTimeL(0L);
			}
			@SuppressWarnings("unchecked")
			List<ActionItem> itemList = (List<ActionItem>) new ArrayList<ActionItem>();
			String itemsjsondata = request.getParameter("items");
			if (ValidateUtils.isNotEmpty(itemsjsondata)) {
				List<Object> actionitemobjList = GsonTools.getJsonList(itemsjsondata, ActionItem.class);
				for (Object object : actionitemobjList) {
					if (object instanceof ActionItem) {
						ActionItem actionItem = (ActionItem) object;
						itemList.add(actionItem);
					}
				}
			}
			action.setCreateUser(detail.getUserName());
			int action_id = actionService.insertAction(action, itemList);
			actionService.updateAction(action);

			return ResultUtils.instJSONResult(ResultUtils.WEB_SUCCESS_CODE);
		} catch (ErrorException ex) {
			return ResultUtils.instJSONResult(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
		}

	}

	@RequestMapping(value = "/web/action/searchActionById")
	@ResponseBody
	Object searchActionById(HttpServletRequest request, HttpServletResponse response) {

		try {
			// Admin detail = HeaderParser.getUser(request);
			// if (detail == null) {
			// return
			// ResultUtils.instJSONResult(ResultUtils.WEB_LOGIN_FAILED_CODE);
			// }
			String id = request.getParameter("id");
			if (!ValidateUtils.isNotEmpty(id)) {
				return ResultUtils.instJSONResult(ResultUtils.WEB_PARAM_ERROR_CODE);
			}

			Action actions = actionService.searchActionById(Integer.valueOf(id));

			JSONResult jsonResult = ResultUtils.instJSONResult(ResultUtils.WEB_SUCCESS_CODE);
			jsonResult.setData(actions);
			return jsonResult;

		} catch (Exception e) {
			e.printStackTrace();
			return ResultUtils.instJSONResult(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
		}

	}

	@RequestMapping(value = "/web/action/listSearch")
	@ResponseBody
	public Object listActionQuery(HttpServletRequest request, HttpServletResponse response) {
		try {
			// Admin detail = HeaderParser.getUser(request);
			// if (detail == null) {
			// throw new ErrorException(ResultUtils.WEB_PARAM_ERROR_CODE);
			// }
			/**
			 * 按类别查询
			 */
			Integer actionType = null;
			String paramActionType = request.getParameter("actionType");
			if (ValidateUtils.isNotEmpty(paramActionType)) {
				actionType = Integer.parseInt(paramActionType);
			}
			/**
			 * 按状态查询
			 */
			Integer status = null;
			String paramStatus = request.getParameter("status");
			if (ValidateUtils.isNotEmpty(paramStatus)) {
				status = Integer.parseInt(paramStatus);
			}
			/**
			 * 按开始时间，结束时间查询
			 */
			String paramSdate = request.getParameter("sdate");
			String paramEdate = request.getParameter("edate");
			Long searchStartTime = null;
			Long searchFinalTime = null;
			if (ValidateUtils.isValidDate(paramSdate) && ValidateUtils.isValidDate(paramEdate)) {
				searchStartTime = DateUtils.str2DateL(paramSdate);
				searchFinalTime = DateUtils.str2DateL(paramEdate);
			}
			/**
			 * 按活动是否置顶 是否轮播查询
			 */
			Integer loopStatus = null;
			String paramLoopStatus = request.getParameter("loopStatus");
			if (ValidateUtils.isNotEmpty(paramLoopStatus)) {
				loopStatus = Integer.parseInt(paramLoopStatus);
			}
			/**
			 * 按title标题查询
			 */
			String title = null;
			String paramTitle = request.getParameter("title");
			if (ValidateUtils.isNotEmpty(paramTitle)) {
				title = new String(paramTitle.getBytes("ISO-8859-1"), "UTF-8");
			}
			String page = request.getParameter("page");
			PagingInfo pagingInfo = new PagingInfo();
			int firstResult = 0;
			if (ValidateUtils.isNotEmpty(page)) {
				firstResult = (Integer.parseInt(page) - 1) * SystemWebConstant.DEFAULT_PAGE_SIZE;
				pagingInfo.setCurrentPage(Integer.parseInt(page));
			}
			Long totalCount = actionService.searchActionListCount(title, actionType, status, searchStartTime,
					searchFinalTime, loopStatus);
			List<Action> listResult = actionService.searchActionList(title, actionType, status, searchStartTime,
					searchFinalTime, loopStatus, firstResult, SystemWebConstant.DEFAULT_PAGE_SIZE);

			List<HashMap<String, Object>> actionMapList = new ArrayList<HashMap<String, Object>>();
			for (Action action : listResult) {
				HashMap<String, Object> actionMap = new HashMap<String, Object>();
				actionMap.put("cdateL", action.getCdateL());
				actionMap.put("sdateL", action.getSdateL());
				actionMap.put("edateL", action.getEdateL());
				actionMap.put("title", action.getTitle());
				actionMap.put("status", action.getStatus());

				actionMapList.add(actionMap);

			}

			JSONResult result = ResultUtils.instJSONResult(ResultUtils.WEB_SUCCESS_CODE);
			JsonPagingData jsonPagingData = new JsonPagingData();
			pagingInfo.setTotal(totalCount.intValue());
			jsonPagingData.setPaging(pagingInfo);
			jsonPagingData.setList(listResult);
			result.setData(jsonPagingData);
			return result;

		} catch (ErrorException ex) {
			return ResultUtils.instJSONResult(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
		} catch (Exception ex) {
			ex.printStackTrace();

			return ResultUtils.instJSONResult(ResultUtils.WEB_FAILED_CODE);
		}

	}

	/**
	 * 返回修改页面
	 * 
	 * @param request
	 * @param response
	 * @return
	 */

	@RequestMapping(value = "web/action/updatePage")
	public String updateActionPage(HttpServletRequest request, HttpServletResponse response) {
		try {
			initUpdateActionPage(request);
			initCreateActionpage(request);
		} catch (ErrorException e) {
			e.printStackTrace();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return "/pages/content/action/action-edit";
	}

	@RequestMapping(value = "/web/action/deleteSave", method = RequestMethod.POST)
	@ResponseBody
	public Object delete(HttpServletRequest request, HttpServletResponse response) {
		try {

			Admin detail = HeaderParser.getUser(request);
			if (detail == null) {
				throw new ErrorException(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
			}
			Integer id = Integer.valueOf(request.getParameter("id"));
			Action action = actionService.searchActionById(id);
			if (action != null) {
				action.setStatus(-2);
				actionService.updateAction(action);
			}
			return ResultUtils.instJSONResult(ResultUtils.WEB_SUCCESS_CODE);
		} catch (ErrorException e) {
			e.printStackTrace();
			return ResultUtils.instJSONResult(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultUtils.instJSONResult(ResultUtils.WEB_FAILED_CODE);
		}

	}

	@RequestMapping(value = "web/action/updateStatus", method = RequestMethod.POST)
	@ResponseBody
	public Object setStauts(HttpServletRequest request, HttpServletResponse response) {

		try {
			Admin detail = HeaderParser.getUser(request);
			if (detail == null) {
				throw new ErrorException(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
			}
			Integer id = Integer.valueOf(request.getParameter("id"));
			Action editAction = actionService.searchActionById(id);
			String status = request.getParameter("status");
			if (ValidateUtils.isNotEmpty(status)) {
				if (Integer.valueOf(status) == 0) {
					editAction.setStatus(1);
				} else if (Integer.valueOf(status) == 1) {
					editAction.setStatus(-1);
					editAction.setLoopStatus(0);
				} else {
					editAction.setLoopStatus(0);
					editAction.setStatus(0);
				}
			}
			actionService.updateAction(editAction);
			return ResultUtils.instJSONResult(ResultUtils.WEB_SUCCESS_CODE);
		} catch (ErrorException e) {
			e.printStackTrace();
			return ResultUtils.instJSONResult(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultUtils.instJSONResult(ResultUtils.WEB_FAILED_CODE);
		}

	}

	@RequestMapping(value = "web/action/updateShow")
	@ResponseBody
	public Object setConfiguration(HttpServletRequest request, HttpServletResponse response) throws ErrorException {
		try {
			Admin detail = HeaderParser.getUser(request);
			if (detail == null) {
				throw new ErrorException(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
			}
			Integer id = Integer.valueOf(request.getParameter("id"));
			Action editAction = actionService.searchActionById(id);
			String isLoop = request.getParameter("isloop");
			editAction.setLoopStatus(0);
			if (ValidateUtils.isNotEmpty(isLoop)) {
				if (Integer.valueOf(isLoop) == 1) {
					editAction.setLoopStatus(1);
				}
			}
			String sort = request.getParameter("order");
			if (ValidateUtils.isNotEmpty(sort)) {
				editAction.setSort(Double.parseDouble(sort));
			}
			String status_str = request.getParameter("status");
			if (ValidateUtils.isNotEmpty(status_str)) {
				editAction.setStatus(Integer.valueOf(status_str));
			}
			actionService.updateAction(editAction);
			return ResultUtils.instJSONResult(ResultUtils.WEB_SUCCESS_CODE);
		} catch (ErrorException e) {
			e.printStackTrace();

			return ResultUtils.instJSONResult(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
		} catch (Exception e) {
			return ResultUtils.instJSONResult(ResultUtils.WEB_FAILED_CODE);
		}

	}

	@RequestMapping(value = "web/action/updateSave")
	@ResponseBody
	public Object update(HttpServletRequest request, HttpServletResponse response) {
		try {
			Integer id = Integer.valueOf(request.getParameter("id"));
			Action actionExist = actionService.searchActionById(id);
			if (actionExist != null) {
				String title = request.getParameter("title");
				if (ValidateUtils.isNotEmpty(title)) {
					actionExist.setTitle(title);
				}
				if (ValidateUtils.isNotEmpty(title)) {
					actionExist.setShareContent(title);
				}
				String action_type = request.getParameter("type");
				if (ValidateUtils.isNotEmpty(action_type) && ValidateUtils.isValidInteger(action_type)) {
					actionExist.setActionType(Integer.parseInt(action_type));
				}
				String intro = request.getParameter("intro");
				if (ValidateUtils.isNotEmpty(intro)) {
					actionExist.setIntro(intro);
				}
				String sdate = request.getParameter("sdate");
				String edate = request.getParameter("edate");
				if (ValidateUtils.isValidDate(sdate) && ValidateUtils.isValidDate(edate)) {
					SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
					Calendar calendar = Calendar.getInstance(Locale.CHINA);
					try {
						calendar.setTime(dateFormat.parse(sdate));
					} catch (ParseException e) {
						e.printStackTrace();
					}
					actionExist.setSdateL(calendar.getTimeInMillis());
					try {
						calendar.setTime(dateFormat.parse(edate));
					} catch (ParseException e) {
						e.printStackTrace();
					}
					actionExist.setEdateL(calendar.getTimeInMillis());
				}
				String maxAppliment = request.getParameter("maxAppliment");
				if (ValidateUtils.isNotEmpty(maxAppliment)) {
					int maxappliment = Integer.valueOf(maxAppliment);
					actionExist.setMaxAppliment(maxappliment);
				} else {
					actionExist.setMaxAppliment(-1);
				}
				String image = request.getParameter("image");
				if (ValidateUtils.isNotEmpty(image)) {
					actionExist.setImage(image);
				}
				String sort = request.getParameter("sort");
				if (ValidateUtils.isNotEmpty(sort)) {
					actionExist.setSort(Double.parseDouble(sort));
				}
				String url = request.getParameter("url");
				if (ValidateUtils.isNotEmpty(url)) {
					actionExist.setUrl(url);
					if (Integer.valueOf(action_type) == 2) {
						actionExist.setShareUrl(url);
					}
				}
				String istop_str = request.getParameter("istop");
				if (ValidateUtils.isNotEmpty(istop_str)) {
					actionExist.setLoopStatus(Integer.valueOf(istop_str));
				} else {
					actionExist.setLoopStatus(0);
				}
				String ispay = request.getParameter("isPay");
				if (ValidateUtils.isNotEmpty(ispay)) {
					if ("on".equals(ispay)) {
						actionExist.setPayStatus(1);
						String strpayType = request.getParameter("payType");
						if (ValidateUtils.isNotEmpty(strpayType)) {
							Integer payType = Integer.valueOf(strpayType);
							if (PayType.BYCAR.getTypeId() == payType) {
								actionExist.setPayType(PayType.BYCAR.getTypeId());
							} else {
								actionExist.setPayType(PayType.BYPEOPLE.getTypeId());
							}
						}
						String pay = request.getParameter("pay");
						if (ValidateUtils.isNotEmpty(pay) && ValidateUtils.isValidNumber(pay)) {
							actionExist.setPayAmount(Float.parseFloat(pay));
						}
						String payName = request.getParameter("payname");
						if (ValidateUtils.isNotEmpty(payName)) {
							actionExist.setPayName(payName);
						}
						String payEndTime = request.getParameter("payEndTime");
						if (ValidateUtils.isNotEmpty(payEndTime) && ValidateUtils.isValidDate(payEndTime)) {
							actionExist.setPayEndTimeL(DateUtils.str2DateL(payEndTime));
						}
					} else {
						actionExist.setPayStatus(Action.ACTION_PAY_FALSE);
						actionExist.setPayName("");
						actionExist.setPayAmount(0.0f);
						actionExist.setPayEndTimeL(0L);
					}

				} else {
					actionExist.setPayStatus(Action.ACTION_PAY_FALSE);
					actionExist.setPayName("");
					actionExist.setPayAmount(0.0f);
					actionExist.setPayEndTimeL(0L);
				}
				List<ActionItem> itemList = new ArrayList<ActionItem>();
				String itemsjsondata = request.getParameter("items");
				if (ValidateUtils.isNotEmpty(itemsjsondata)) {
					List<Object> actionitemobjlist = GsonTools.getJsonList(itemsjsondata, ActionItem.class);
					for (Object object : actionitemobjlist) {
						if (object instanceof ActionItem) {
							ActionItem actionItem = (ActionItem) object;
							actionItem.setActionId(actionExist.getActionId());
							itemList.add(actionItem);
						}

					}
				}
				actionService.updateAction(actionExist, itemList);
				return ResultUtils.instJSONResult(ResultUtils.WEB_SUCCESS_CODE);
			} else {
				return ResultUtils.instJSONResult(ResultUtils.WEB_FAILED_CODE);
			}

		} catch (ErrorException e) {
			e.printStackTrace();
			return ResultUtils.instJSONResult(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultUtils.instJSONResult(ResultUtils.WEB_FAILED_CODE);
		}

	}

	@RequestMapping(value = "/web/test")
	@ResponseBody
	void test(HttpServletRequest request, HttpServletResponse response) {

		try {
			actionService.test();
		} catch (Exception e) {
		}

	}

}
